import time
from app.jobs.pdfparser.internal.logic.task import KqPaperMeta, PDFTask, PDFTaskType
from app.jobs.pdfparser.internal.svc.servicecontext import ServiceContext
from common.utils import logger


class PDFDeleteTask(PDFTask):
    def __init__(self, svcCtx: ServiceContext, payload):
        super().__init__(task_type=PDFTaskType.DELETE)
        self.svcCtx = svcCtx
        self.payload = payload
        
    def handle(self):
        paper_meta = None
        try:
            start = time.time()
            
            paper_meta = KqPaperMeta.from_json(self.payload)
            if paper_meta.user_id == 0 or not paper_meta.id:
                raise ValueError("invalid paper_meta, id or user_id invalid")
            
            self.svcCtx.paper_segment_model.delete_by(paper_meta.user_id, paper_meta.id)
            self.svcCtx.paper_segment_model.delete_meta(paper_meta.user_id, paper_meta.id)
            
            duration_ms = round((time.time() - start) * 1000, 1)
            logger.my_logger().info(f'【PDFDeleteTask】delete file id: {paper_meta.id} success', extra={'duration': duration_ms})
        except Exception as e:
            if paper_meta is not None:
                logger.my_logger().info(f'【PDFDeleteTask】delete file id: {paper_meta.id} failed, Exception {str(e)} happen')
            else:
                logger.my_logger().info(f'【PDFDeleteTask】delete file failed, Exception {str(e)} happen')